<template>
  <view>
    <view class="search-container">
      <uni-search-bar @input="input"
                      class="search-box"
                      radius=50
                      cancelButton='none'
                      placeholder='请输入搜索商品'></uni-search-bar>
    </view>
    <!-- 当searchList为空时显示历史记录lis，当searchList不为空时显示搜索列表 -->
    <view class="sugg-list"
          v-if="searchList.length>0">
      <view class="sugg-item"
            v-for="item in searchList"
            :key="item.goods_id">
        <!-- 点击每一个搜索内容跳转到详情页 -->
        <text class="goods-name"
              @click="toDetail(item.goods_id)">{{item.goods_name}}</text>
      </view>

    </view>
    <view v-else
          class="history-box">
      <view class="history-title">
        <text>搜索历史</text>
        <!-- 点击垃圾箱删除所有的历史纪录 -->
        <uni-icons type="trash-filled"
                   size="25"
                   @click="deleteHostoryList"
                   class="uni-tag"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag v-for="item in historyList"
                 :text="item"
                 type="default"
                 circle
                 :key="item"
                 @click="toGoodList(item)" />
      </view>
    </view>
  </view>
</template>
<script>
export default ({
  data () {
    return {
      timeId: null,
      searchList: [],
      // 搜索历史数据，倒叙，去重
      historyList: []
    };
  },
  onLoad () {
    // console.log(uni.getStorageSync('historyList'));
    this.historyList.push(...uni.getStorageSync('historyList'))
  },

  methods: {
    toGoodList (keyword) {
      console.log(111);
      uni.navigateTo({
        url: '/subpckg/goods_lists/goods_list?query=' + keyword
      })
    },
    // 实现防抖功能
    input (e) {

      clearInterval(this.timeId)
      this.timeId = setTimeout(async () => {
        // console.log(e);
        // 去重
        // this.historyList.forEach((item, index) => {
        //   if (item === e) {
        //     this.historyList.splice(index, 1)
        //   }
        // });
        let index = this.historyList.findIndex(item => {
          return item === e
        })
        console.log(index);
        if (index > -1) {
          this.historyList.splice(index, 1)
        }
        // 倒叙
        this.historyList.unshift(e)
        uni.setStorageSync('historyList', this.historyList)
        if (e.trim() === '') {
          uni.showToast({
            title: '搜索框不能为空',
            icon: 'none'
          })
          this.searchList = ''
          return
        }
        let res = await uni.$request({
          url: 'goods/qsearch',
          data: {
            query: e.trim()
          }
        })
        if (res.meta.status == 200) {
          this.searchList = res.message
        }
        if (this.searchList.length === 0) {
          uni.showToast({
            title: '暂时没有此类商品',
            icon: 'none'
          })
        }
      }, 500)

    },
    toDetail (id) {
      uni.navigateTo({
        url: `/subpckg/detail/index?id=${id}`
      })
    },
    deleteHostoryList () {
      // 刷新页面
      this.historyList = []
      // 删除所所有本地历史记录
      uni.clearStorageSync('historyList')


    }
  }
})

</script>

<style lang="scss" scoped>
.search-container {
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
    ::v-deep .uni-searchbar {
      /* #ifndef APP-NVUE */
      display: flex;
      /* #endif */
      flex-direction: row;
      position: relative;
      padding: 16rpx;
      /* 将默认的 #FFFFFF 改为 #C00000 */
      background-color: #c00000;
    }
  }
}
.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    ::v-deep .uni-tag {
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}

.sugg-list {
  padding: 0 5px;

  .sugg-item {
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .goods-name {
      // 文字不允许换行（单行文本）
      white-space: nowrap;
      // 溢出部分隐藏
      overflow: hidden;
      // 文本溢出后，使用 ... 代替
      text-overflow: ellipsis;
      margin-right: 3px;
    }
  }
}
</style>